<?php

class Third_Plugins_Acl extends Zend_Controller_Plugin_Abstract
{

    protected $_auth = null;

    protected $_acl = null;
	
    private $_noauth = array('module' => 'third',
                             'controller' => 'error',
                             'action' => 'login');

    private $_noacl = array('module' => 'third',
                            'controller' => 'error',
                            'action' => 'privileges');
    
    public function __construct(Zend_Auth $auth, Zend_Acl $acl)
    {
        $this->_auth = $auth;
        $this->_acl = $acl;
    }

    public function preDispatch(Zend_Controller_Request_Abstract $request)
    {
    	$logged = $this->_auth->getStorage()->read();

        if ($this->_auth->hasIdentity() && $logged->nivel) {
            $role = $logged->nivel;

        } else {
            $role = 'visitante';
        }

        // MAPEIA RESOURCE DE ACORDO COM DADOS DA ACTION ATUAL
        $resourceModule = $request->module;
        $resourceController = $request->module.':'.$request->controller;
		$resourceAction = $request->module.':'.$request->controller.':'.$request->action;

        if ( (!$this->_acl->has($resourceModule)) ) {
            $resourceModule = null;
        }
     	if ( (!$this->_acl->has($resourceController)) ) {
            $resourceController = null;
        }
    	if ( (!$this->_acl->has($resourceAction)) ) {
            $resourceAction = null;
        }


/*
        		(!$this->_acl->isAllowed($role, $resourceModule ) ) ||
        		(!$this->_acl->isAllowed($role, $resourceController ) ) ||
 * */
        if ( 
        		(!$this->_acl->isAllowed($role, $resourceAction ) )
        	) {
            if ($this->_auth->hasIdentity()) {
                // authenticated, denied access, forward to index
                $request->setModuleName( $this->_noacl['module'] );
                $request->setControllerName( $this->_noacl['controller'] );
                $request->setActionName( $this->_noacl['action'] );
            } else {
                // not authenticated, forward to login form
                $request->setModuleName( $this->_noauth['module'] );
                $request->setControllerName( $this->_noauth['controller'] );
                $request->setActionName( $this->_noauth['action'] );
            }
        }
    }
}